import 'package:flutter/material.dart';
import 'package:flutter_van_android/pages/home_page.dart';
import 'package:flutter_van_android/utils/router_manager.dart';
import 'package:oktoast/oktoast.dart';

import '../repositories/user_repository.dart';

class LoginPage extends StatefulWidget with RouterBridge<void> {
  const LoginPage({super.key});

  @override
  State<StatefulWidget> createState() {
    return _LoginPageState();
  }
}

class _LoginPageState extends State<LoginPage> {
  // 控制输入框的内容
  final TextEditingController _usernameController = TextEditingController();
  final TextEditingController _passwordController = TextEditingController();

  // 提交登录请求
  Future<void> _login() async {
    final String phone = _usernameController.text.trim();
    final String smsCode = _passwordController.text.trim();

    if (phone.isEmpty || smsCode.isEmpty) {
      showToast("手机或验证码不能为空");
      return;
    }

    // 调用登录 API
    var bool = await login(phone, smsCode);
    if (bool) {
      if (!mounted) return; // 如果当前的 State 已经销毁，则不再执行后续代码
      showToast("登录成功！");
      Navigator.pushReplacementNamed(context, RouterHelper.typeName(HomePage));
    } else {
      // showToast("登录失败！");
    }
  }

  @override
  void dispose() {
    // 清理控制器
    _usernameController.dispose();
    _passwordController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text("登录")),
      body: Padding(
        padding: const EdgeInsets.all(20.0),
        child: Column(
          children: [
            // 用户名输入框
            TextField(
              controller: _usernameController,
              decoration: InputDecoration(
                labelText: "用户名",
                border: OutlineInputBorder(),
                prefixIcon: Icon(Icons.person),
              ),
            ),
            SizedBox(height: 16),

            // 密码输入框
            TextField(
              keyboardType: TextInputType.number,
              controller: _passwordController,
              decoration: InputDecoration(
                labelText: "验证码",
                border: OutlineInputBorder(),
                prefixIcon: Icon(Icons.sms),
              ),
            ),
            SizedBox(height: 24),

            // 登录按钮
            SizedBox(
              child: ElevatedButton(
                onPressed: _login,
                style: ElevatedButton.styleFrom(minimumSize: Size(200, 50)),
                child: Text("登录"),
              ),
            ),
          ],
        ),
      ),
    );
  }
}
